<!--
用法：umsdk-file-upload  基于umsdk的文件上传组件
    参数 params :  object{}  上传文件接口对应参数
        actionsOneGroup:  array[]  1: 拍照  2:从相册中选择  3: 文件  4:拍照  (长按拍视频)  1,4 不能同传
        maximagescount: string   upload为2 时 最大上传数
        disabled: 是否禁止
-->
<template id="qm-picture-upload">
    <f7-list class="pic_upload">
        <template v-if="!disabled">
            <span class="legend" v-if="showLegend.show" @click="openLegendFile(showLegend.id)">
                <img :src="getDownTem(showLegend.id)" alt="">
                <div>图例</div>
            </span>
            <span class="pic-span"
                  v-for="(file, index) in dbImgList"
                  :key="file.attachmentId"
                  :title="file.fileName">
                <div class="img-div">
                    <img class="img-attachement"
                         :src="getFileThumb(file)"
                         @click="openPhotoBrowser(file,index)" />
                </div>
                <span 
                    class="removeBox" 
                    v-if="!disabled && (params.hideDelKey?file[params.hideDelKey]!=params.hideDelKeyValue:true)"
                    @click="removeDbFile(file)"
                >
                    <van-icon name="cross" />
                </span>
                <div class="offline_tag" v-if="file.reserved1=='offline'">离线</div>
            </span>
            <template v-if="uploadImgList.length>0">
                <span v-for="(file, index) in uploadImgList"
                    :key="file.id + index"
                    :title="file.name">
                    <div class="img-div">
                        <img class="img-attachement"
                            :src="getFileThumb(file, true)"
                            @click="openPhotoBrowser(file,dbfiles.length + index,true)" />
                    </div>
                    <span class="removeBox" v-if="!disabled" @click="removeFile(file)">
                        <van-icon name="cross" />
                    </span>
                    <div class="offline_tag" v-if="showOffline">离线</div>
                </span>
            </template>

            <span class="addPic" v-if="!disabled&&acceptCount>(files.length+dbfiles.length)" @click="openUpload"></span>

            <div class="file-list" v-if="dbFileList.length>0">
                <div v-for="(file, index) in dbFileList" :key="file.attachmentId" class="file-list-div">
                    <!-- 序号 -->
                    <section @click="openPhotoBrowser(file, index)">
                        <div class="file-index" v-if="showIndex == true">
                            <span>{{ index + 1 }}、</span>
                        </div>
                        <img :src="require(`@/assets/img/file/${fileTypeSrc(file)}.png`)" alt="" />
                        <span class="file-name">{{ file.fileName }}</span>
                    </section>
                    <van-icon name="close" class="remove-icon" @click="removeDbFile(file)"/>
                </div>
            </div>
            <div class="file-list" v-if="uploadFileList.length>0">
                <div v-for="(file, index) in uploadFileList" :key="file.attachmentId" class="file-list-div">
                    <section @click="openPhotoBrowser(file, dbFileList.length + index,true)">
                        <!-- 序号 --> 
                        <div class="file-index" v-if="showIndex == true">
                            <span>{{ index + 1 }}、</span>
                        </div>
                        <img :src="require(`@/assets/img/file/${fileTypeSrc(file)}.png`)" alt="" />
                        <span class="file-name">{{ file.name }}</span>
                    </section>
                    <van-icon name="close" class="remove-icon" @click="removeFile(file,index)"/>
                </div>
            </div>
        </template>
        <template v-else>
            <!-- new:图片与文件分开展示 -->
            <div class="imgList">
                <span class="legend" v-if="showLegend.show" @click="openLegendFile(showLegend.id)">
                    <img :src="getDownTem(showLegend.id)" alt="">
                    <div>图例</div>
                </span>
                <span v-for="(file, index) in dbImgList" :key="file.attachmentId">
                    <div class="img-div">
                        <div class="img-index" v-if="showIndex == true">
                            <span>{{ index + 1 }}</span>
                        </div>
                        <img class="img-attachement" :src="getFileThumb(file)" @click="openPhotoBrowserImg(file, index)" />
                    </div>
                    <div v-if="file.code" style="font-size: 12px">{{ file.code }}</div>
                    <div class="offline_tag" v-if="file.reserved1=='offline'">离线</div>
                </span>
            </div>
            <div class="file-list" v-if="dbFileList.length>0">
                <div v-for="(file, index) in dbFileList" :key="file.attachmentId" class="file-list-div" @click="openPhotoBrowserImg(file, index)">
                    <!-- 序号 -->
                    <div class="file-index" v-if="showIndex == true">
                        <span>{{ index + 1 }}、</span>
                    </div>
                    <img :src="require(`@/assets/img/file/${fileTypeSrc(file)}.png`)" alt="" />
                    <span class="file-name">{{ file.fileName }}</span>
                </div>
        </div>
        </template>
    </f7-list>
</template>
<script>
import Util from "@/libs/framework/util";
import Config from "@/libs/config";
export default {
    props: {
        params: {
            type: Object,
            default: ()=>({}),
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        actionsOneGroup: {
            type: Array,
            default: ()=>{
                return [1, 2, 3]
            }
        },
        // deleteUrl: {
        //     type: String,
        //     default: Config.api.delFileApi,
        // },
        /** 图片类型 */
        picExtension: {
            type: Array,
            default: () => {
                return ["jpg", "png", "jpeg", "bmp", "webp", "gif"];
            },
        },
        maximagescount: {
            type: Number,
            default: 9
        },
        // 是否显示图例
        showLegend:{
            type:Object,
            default:()=>{
                return {
                    show:false,
                }
            }
        },
        defaultFiles: {
            type: Array,
            default: () => {
                return [];
            },
        },
        isDefaultFile:{
            type:Boolean,
            default:false,
        },
        showOffline:{
            type:Boolean,
            default:false
        },
        acceptCount:{
            type:Number,
            default:Infinity
        },
    },
    data () {
        return {
            downUrl: Config.api.download,
            downThumb: Config.api.downThumb,
            getUrl: '/api/base/fileupload/getFiles',
            deleteUrl: Config.api.delFile,
            postUrl: Config.api.upload,
            files: [],
            dbfiles: [],
            fileThumbPic: [
                "avi",
                "doc",
                "docx",
                "mp4",
                "pdf",
                "ppt",
                "pptx",
                "rar",
                "txt",
                "xls",
                "xlsx",
                "zip",
            ],
            dbImgList:[],
            dbFileList:[],
            uploadImgList:[],
            uploadFileList:[],
        };
    },
    mounted () {
        
    },
    created () {
        if(this.isDefaultFile){
            this.mapFileList(this.defaultFiles)
        }else{ // 否则请求文件
            if (this.params.dataKey && this.params.bizType) {
                this.fnInit();
            }
        }
    },
    methods: {
        fnInit () {
            try {
                let self = this;
                let url = self.getUrl;
                localStorage.setItem('aaurl',url)
                // 取消监听
                // if (this.unwacth) this.unwacth();
                self.$f7.request.post(url, self.params, (r) => {
                    r = JSON.parse(r);
                    if (r?.success) {
                        localStorage.setItem('r.success',JSON.stringify(r.success))
                        self.mapFileList(r.parameters.files)
                        return;
                    }
                    self.$framework.$f7.dialog.toast("获取文件失败");
                });
            } catch (error) {
                localStorage.setItem('getFileError',error)
            }
        },
        getImgOrFile(item,imgField,fileField,isUpload){
            let imgType = [".png", ".jpeg", ".jpg", 'bmp'];
            if(!item.fileName) item.fileName=item.name
            if(!item.fileType) item.fileType=item.fileName.substring(item.fileName.lastIndexOf("."));
            // 上传
            if(isUpload){
                // 图片类型
                if (imgType.indexOf(item.fileType) != -1) {
                    this[imgField].push(item);
                } else {// 文件类型
                    this[fileField].push(item);
                }
            }else{ // 删除
                if (imgType.indexOf(item.fileType) != -1) {
                    this[imgField].splice(this[imgField].findIndex(file=>file.key==item.key),1);
                } else {// 文件类型
                    this[fileField].splice(this[fileField].findIndex(file=>file.key==item.key),1)
                }
            }
            this.$forceUpdate()
        },
        fileTypeSrc (item) {
            // 文件类型，用于展示文件类型图片
            let typeList = [
                ".avi",
                ".doc",
                ".docx",
                ".jpeg",
                ".jpg",
                ".pdf",
                ".mp4",
                ".png",
                ".ppt",
                ".pptx",
                ".rar",
                ".txt",
                ".xls",
                ".xlsx",
                ".zip",
            ];
            if(!item.fileName&&item.name) item.fileName=item.name
            if(!item.fileType&&item.fileName) item.fileType=item.fileName.substring(item.fileName.lastIndexOf("."))
            return typeList.indexOf(item.fileType) != -1
                ? item.fileType.substr(1)
                : "default";
        },
        mapFileList(fileList){
            try {
                let self=this
                self.dbfiles = fileList || [];
                // 如果禁用状态，即查看状态，需要分图片以及pdf等文件类型的分类
                self.dbImgList = [];
                self.dbFileList = [];
                let imgType = [".png", ".jpeg", ".jpg",'.bmp','.BMP','.JPEG','.PNG','.JPG'];
                fileList.map((item) => {
                    if(!item.fileType) item.fileType=item.fileName.substring(item.fileName.lastIndexOf("."));
                    localStorage.setItem('item.fileType',item.fileType)
                    // 图片类型
                    if (imgType.indexOf(item.fileType) != -1) {
                        self.dbImgList.push(item);
                    } else {
                        // 文件类型
                        self.dbFileList.push(item);
                    }
                    this.$forceUpdate()
                });
                if (self.params) {
                    self.params.sort = self.dbfiles.length + 1;
                }
            } catch (error) {
                localStorage.setItem('mapFileListError',error)
                console.log(error);
            }
        },
        openLegendFile(attachmentId){
            let photos=[this.getDownTem(attachmentId)]
            umSdk.showPhotos({
                imgs: photos, // 图片地址数组，必填
                index: 0, // 从第几个开始浏览，必填
                success: function () { },
                fail: function (err) { }
            })
        },
        getDownTem(id){
            return `${Config.api.download}?attachmentId=${id}`
        },
        openUpload () {
            var self = this;
            let url = self.postUrl + '?';
            Object.keys(self.params).forEach(e => {
                url += e + '=' + self.params[e] + '&';
            })
            url += `championsoft=${encodeURIComponent(this.$f7.data.authToken)}`
            umSdk.fileUpload({
                uploaditem: self.actionsOneGroup, // 可选择项 1:拍照 2:从相册中选择 3:文件 4:拍照（支持长按转拍视频）注意：1和4不能同时传
                uploadurl: url, // 文件上传的位置，文件服务器地址
                itemproperty: {
                    maximagescount: self.maximagescount
                },// key 为 2时：maximagescount代表选择图片时的最大数量
                success: function (res) {
                    self.$f7.dialog.alert("上传成功")
                    self.$emit("onSuccess");
                    res.forEach(e => {
                        if (typeof e == 'string') {
                            e = JSON.parse(e)
                        }
                        self.files.push(e.parameters.file)
                        self.$emit("success", e.parameters.file);
                        localStorage.setItem('successFile',JSON.stringify(e.parameters.file))
                        self.getImgOrFile(e.parameters.file,'uploadImgList','uploadFileList',true)
                    })
                },
                fail: function (err) {
                    self.$f7.dialog.alert(err)
                }
            })
        },
        getFileThumb (file, isUpload) {
            var defaultPic = "static/img/file/default.png";
            var fName = file.fileName;
            if (isUpload) {
                fName = file.name;
            }

            if (!file.fileType && fName) {
                file.fileType = fName.substring(fName.lastIndexOf("."));
            }

            var extension = file.fileType?.replace(".", "");
            if (extension) {
                extension = extension.toLowerCase();
                file.isPic = this.picExtension.includes(extension);
            }

            if (file.isPic === true) {
                if (isUpload) {
                    return `${this.downThumb}?attachmentId=${file.key}&championsoft=${encodeURIComponent(this.$f7.data.authToken)}`;
                }
                return `${this.downThumb}?attachmentId=${file.attachmentId}&championsoft=${encodeURIComponent(this.$f7.data.authToken)}`;
            }

            if (this.fileThumbPic.includes(extension)) {
                return `static/img/file/${extension}.png`;
            }

            return defaultPic;
        },
        removeDbFile (file) {
            var self = this;
            let attachmentId = file.attachmentId;
            if (attachmentId != undefined) {
                self.$f7.dialog.confirm("该文件已上传成功，确定要删除吗？", (r) => {
                    if (r) {
                        self.$f7.preloader.show();
                        self.$f7.request.post(
                            self.deleteUrl,
                            { attachmentId: attachmentId },
                            (r) => {
                                r = JSON.parse(r);
                                self.$f7.preloader.hide();
                                if (r && r.success) {
                                    self.dbfiles.splice(self.dbfiles.indexOf(file), 1);
                                    let dbIndex=self.dbImgList.findIndex(item=>item.attachmentId==attachmentId)
                                    let dbFileIndex=self.dbFileList.findIndex(item=>item.attachmentId==attachmentId)
                                    if(dbIndex!=-1){
                                        self.dbImgList.splice(dbIndex, 1);
                                    }
                                    if(dbFileIndex!=-1){
                                        self.dbFileList.splice(dbFileIndex, 1);
                                    }
                                    self.$framework.$f7.dialog.toast("文件删除成功");
                                } else {
                                    self.$framework.$f7.dialog.toast(r.message || "文件删除失败");
                                }
                            },
                            (e) => {
                                self.$f7.preloader.hide();
                                self.$framework.$f7.dialog.toast("文件删除失败");
                            }
                        );
                    }
                });
            } else {
                self.dbfiles.splice(self.files.indexOf(file), 1);
            }
        },
        removeFile (file,showMsg=true) {
            var self = this;
            let attachmentId = file.key;
            if (file || attachmentId != undefined) {
                self.$f7.dialog.confirm("该文件已上传成功，确定要删除吗？", (r) => {
                    if (r) {
                        self.$f7.preloader.show();
                        self.$f7.request.post(
                            self.deleteUrl,
                            {
                                attachmentId: attachmentId
                            },
                            (r) => {
                                r = JSON.parse(r);
                                self.$f7.preloader.hide();
                                if (r && r.success) {
                                    if (attachmentId == undefined) {
                                        self.$refs[self.uploadId].remove(file);
                                    } else {
                                        self.files.splice(self.files.indexOf(file), 1);
                                        self.getImgOrFile(file,'uploadImgList','uploadFileList',false)
                                    }
                                    if(showMsg)self.$framework.$f7.dialog.toast("文件删除成功");
                                } else {
                                    self.$framework.$f7.dialog.toast(r.message || "文件删除失败");
                                }
                            },
                            (e) => {
                                self.$f7.preloader.hide();
                                self.$framework.$f7.dialog.toast("文件删除失败");
                            }
                        );
                    }
                });
            }
        },
        openPhotoBrowser (file, indexs, isUpload) {
            var self = this;
            let photos = [];

            var attachmentId = file.attachmentId
            var fName = file.fileName;
            if (isUpload) {
                fName = file.name;
                attachmentId = file.key
            }

            if (!file.fileType && fName) {
                file.fileType = fName.substring(fName.lastIndexOf("."));
            }

            var extension = file.fileType?.replace(".", "");
            if (extension) {
                extension = extension.toLowerCase();
                file.isPic = this.picExtension.includes(extension);
            }

            if (file.isPic === true) {
                self.dbImgList.forEach((f) => {
                    photos.push(self.downUrl + "?attachmentId=" + f.attachmentId + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken));
                });
                self.uploadImgList.forEach((f) => {
                    photos.push(self.downUrl + "?attachmentId=" + f.key + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken));
                });
                umSdk.showPhotos({
                    imgs: photos, // 图片地址数组，必填
                    index: indexs, // 从第几个开始浏览，必填
                    success: function () { },
                    fail: function (err) { }
                })
            }
            else {
              if(!fName || fName.lastIndexOf(".")===-1){
                self.$framework.$f7.dialog.alert("非法文件名称");
                return;
              }
                let options = { askRedownload: false };
                // let url = Config.api.download + `?attachmentId=${attachmentId}` + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken);
                let fileType = fName.substring(fName.lastIndexOf("."));
                let  url = `${Config.api.viewOpenFile}/${attachmentId}${fileType}`;
                umSdk.scanFile({
                    downloadurl: url, // 文件预览网络地址
                    filename: fName,
                    success: function () { },
                    fail: function (err) { }
                })
            }
        },
        openPhotoBrowserImg (file, indexs, isUpload) {
            var self = this;
            let photos = [];

            var attachmentId = file.attachmentId
            var fName = file.fileName;
            if (isUpload) {
                fName = file.name;
                attachmentId = file.key
            }

            if (!file.fileType && fName) {
                file.fileType = fName.substring(fName.lastIndexOf("."));
            }

            var extension = file.fileType?.replace(".", "");
            if (extension) {
                extension = extension.toLowerCase();
                file.isPic = this.picExtension.includes(extension);
            }

            if (file.isPic === true) {
                self.dbImgList.forEach((f) => {
                    photos.push(self.downUrl + "?attachmentId=" + f.attachmentId + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken));
                });
                umSdk.showPhotos({
                    imgs: photos, // 图片地址数组，必填
                    index: indexs, // 从第几个开始浏览，必填
                    success: function () { },
                    fail: function (err) { }
                })
            }
            else {
              if(!fName || fName.lastIndexOf(".")===-1){
                self.$framework.$f7.dialog.alert("非法文件名称");
                return;
              }
                let options = { askRedownload: false };
                // let url = Config.api.download + `?attachmentId=${attachmentId}` + '&championsoft=' + encodeURIComponent(this.$f7.data.authToken);
                let fileType = fName.substring(fName.lastIndexOf("."));
                let  url = `${Config.api.viewOpenFile}/${attachmentId}${fileType}`;
                umSdk.scanFile({
                    downloadurl: url, // 文件预览网络地址
                    filename: fName,
                    success: function () { },
                    fail: function (err) { }
                })
            }
        },
        getUploadedCount () {
            var self = this;
            return self.files.length + self.dbfiles.length;
        },
    },
};
</script>
<style scoped lang="less">
.chunk-loading {
    margin: -12px;
    display: flex;
    width: calc(100% + 24px);
}

.chunk-loading .chunk-loading-part {
    height: 25px;
    line-height: 25px;
    flex: 1;
    background: #ccc;
    font-size: 14px;
    color: white;
    text-align: center;
}

.chunk-loading .chunk-loading-part.chunk-loading-part__uploaded {
    background: #28a745;
}

.file-uploads {
    width: 80px;
}

.addPic {
    display: inline-block;
    width: 75px;
    height: 75px;
    border-radius: 3px;
    background: #f8f8f8 url('../../../../assets/img/icon-plus.png') no-repeat
        center;
    background-size: cover;
    margin-left: 8px;
    cursor: pointer;
}
.pic_upload span {
    display: inline-block;
    text-align: center;
    position: relative;
    .offline_tag{
        font-size: 12px;
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        margin: 0;
        background: #00000052;
        color: #fff;
    }
}
.pic_upload {
    padding: 0!important;
    padding-bottom: 10px;
    .legend{
        margin: 0 0 5px 5px;
        vertical-align: top;
        img {
            width: 75px;
            height: 75px;
        }
        div {
            font-size: 12px;
        }
    }
}
.pic_upload span div.img-div {
    width: 75px;
    height: 75px;
    border: 1px solid #e5e5e5;
    margin: 0 auto;
}
.pic_upload span a {
    position: absolute;
    top: -10px;
    right: -10px;
    z-index: 100;
    color: #848484;
}
.pic_upload .demo-gauge {
    top: 0;
    position: absolute;
    left: 50%;
    margin-left: -40px;
}
.f7-icons {
    font-size: 22px;
}
.img-div {
    display: flex;
    justify-content: center;
    align-items: center;
}

.img-attachement {
    width: 100% !important;
    height: 100% !important;
    /* object-fit: contain; */
}
.removeBox{
    position: absolute!important;
    top: 0;
    right: -2px;
    margin: 0;
    padding: 0;
    line-height: 16px;
    height: 18px;
    width: 18px;
    border-bottom-left-radius: 5px;
    background: rgba(0, 0, 0, 0.4);
    /deep/ .van-icon{
        margin: 0;
        padding: 0;
        font-size: 12px;
        color: #fff;
    }
}
.file-list {
    display: flex;
    flex-direction: column;
    margin: 10px 15px 15px 15px;

    &-div {
        display: flex;
        align-items: center;
        color: #0f1826;
        margin-bottom: 12px;

        &:last-child {
            margin-bottom: 0;
        }

        img {
            width: 35px;
            height: 35px;
            margin-right: 10px;
        }

        .file-name {
            flex: 1;
            text-align: left;
            word-break: break-all;
        }

        section{
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex: 1;
        }

        .remove-icon{
            flex-shrink: 0;
        }
    }
}
</style>
